package cn.taobaoke.restful.interceptor;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author bjyangzuo
 * @since 2017-05-17 09:24
 */
@Component
public class AccessInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        request.setAttribute("start_time", System.currentTimeMillis());
        return super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
        long startTime = (long) request.getAttribute("start_time");
        long endTime = System.currentTimeMillis();
        logger.info("Access Finish: {} {} {} ({}ms)", request.getMethod(), request.getRequestURL(), request.getRemoteAddr(), endTime-startTime);
    }

    private final static Logger logger = LogManager.getLogger(AccessInterceptor.class);
}
